<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>上传文件</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
  <input type="file" id="uploaderInput" multiple="multiple" />
  <div id="videoContent" style="visibility:hidden">
    <video id="video" src="" style="width:400px" muted autoplay controls></video>
  </div>
  进度:
  <div id="process">0</div>
</body>

</html>
<script src="./js/jquery-1.12.4.js"></script>
<script src="./js/md5.js"></script>
<script src="./js/axios.js"></script>
<script>

  $('#uploaderInput').on('change', async function () {
    // 获取上传的文件信息
    const file = this.files[0]
    console.log(file)
    // 02-keep-alive原理分析.mp4   --- 02-keep-alive原理分析.xxxxxxx.mp4
    const i = file.name.lastIndexOf('.')
    const filename = file.name.slice(0, i) + '.' + Date.now() + file.name.slice(i)
    // index 标识第几次上传数据
    let index = 0
    // 文件总大小
    const size = file.size;
    // 文件每次上传的大小 固定值，后端提供的 以上传2M为例
    const shareSize = 1024 * 1024 * 2
    // total 代表总共上传多少次 = (文件总大小/每次上传的大小)
    const total = Math.ceil(size / shareSize);
    // 文件hash值
    const hash = await getHash(file)

    upload()

    async function upload() {
      // 定义文件开启切割位置
      const start = index * shareSize;
      // 定义文件结束切割位置
      const end = (index + 1) * shareSize > size ? size : (index + 1) * shareSize
      // 文件切割
      const data = file.slice(start, end);

      const formData = new FormData()
      formData.append('filename', filename)
      formData.append('index', index)
      formData.append('total', total)
      formData.append('hash', hash)
      formData.append('data', data)

      let result = await axios.post('/uploadVideo', formData)
      if (result.data.process) {
        $('#process').html(result.data.process)
      } else {
        $('#process').html('100%')
        $('#videoContent').css('visibility', 'visible')
        $('#video').attr('src', result.data.videoUrl)

      }
      index++;
      if (index < total) {
        upload()
      }
    }

    /*
      filename
      index
      total
      hash
    */
  })

  function getHash(file) {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        const hash = hex_md5(e.target.result);
        resolve(hash);
      }
    })
  }
</script>